package pers.cz.controller;

import cn.hutool.core.date.DateUtil;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import pers.cz.excel.PoiUtils;
import pers.cz.json.JsonUtil;
import pers.cz.model.AutoTestCaseTemplate;
import pers.cz.pub.RespBean;
import pers.cz.service.FileUploadService;
import pers.cz.service.TestCaseTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试案例模板管理
 * @program: PostGirl-panent
 * @description: TestCaseTemplateController
 * @author: Cheng Zhi
 * @create: 2021-11-09 16:07
 **/
@RestController
@Api(tags = "测试案例模板管理接口")
@RequestMapping(path = "/api/testCaseTemplate")
public class TestCaseTemplateController {

    @Autowired
    TestCaseTemplateService service;

    @Autowired
    FileUploadService fileUploadService;

    @ApiOperation(value = "分页查询所有测试案例upload模板")
    @PostMapping(path = "/qeuryAllTestCaseTemplate")
    public List<AutoTestCaseTemplate> qeuryAllTestCaseTemplate(@RequestBody Map map) {

        int pageStart = (int) map.get("pageStart");
        int pageLimit = (int) map.get("pageLimit");

        return service.selectAllTestCaseTemplateByPage(pageStart, pageLimit);
    }

    @ApiOperation(value = "分页查询所有模板总数")
    @GetMapping(path = "/queryCountTemplate")
    public Integer queryCountTemplate() {

        return service.queryCountTemplate();
    }

    @ApiOperation(value = "添加测试案例模板")
    @PostMapping(path = "/addTestCaseTemplate")
    public RespBean addTestCaseTemplate(@RequestBody Map map) {

        String templateName = (String) map.get("templateName");
        String template = (String) map.get("template");
        String firsthandRequest = (String) map.get("firsthandRequest");
        Integer publicTemplateId = (Integer) map.get("publicTemplateId");
        AutoTestCaseTemplate autoTestCaseTemplate = new AutoTestCaseTemplate();
        autoTestCaseTemplate.setCreateTime(DateUtil.date());
        autoTestCaseTemplate.setTemplate(template);
        autoTestCaseTemplate.setFirsthandRequest(firsthandRequest);
        autoTestCaseTemplate.setTemplateName(templateName);
        autoTestCaseTemplate.setPublicTemplateId(publicTemplateId);

        Integer count = service.addTestCaseTemplate(autoTestCaseTemplate);
        return RespBean.ok("成功添加[" + count + "]条");
    }

    @ApiOperation(value = "修改测试案例模板")
    @PostMapping(path = "/updateTestCaseTemplate")
    public RespBean updateTestCaseTemplate(@RequestBody Map map) {

        String templateName = (String) map.get("templateName");
        String template = (String) map.get("template");
        String firsthandRequest = (String) map.get("firsthandRequest");
        Integer id = (Integer) map.get("id");
        AutoTestCaseTemplate autoTestCaseTemplate = new AutoTestCaseTemplate();
        autoTestCaseTemplate.setCreateTime(DateUtil.date());
        autoTestCaseTemplate.setTemplate(template);
        autoTestCaseTemplate.setTemplateName(templateName);
        autoTestCaseTemplate.setFirsthandRequest(firsthandRequest);
        autoTestCaseTemplate.setId(id);

        Integer count = service.updateTestCaseTemplate(autoTestCaseTemplate);
        return RespBean.ok("成功修改[" + count + "]条");
    }

    @ApiOperation(value = "根据原始报文自动解析出一个模板")
    @PostMapping(path = "/autoAnaylizeTemplate")
    public Map<String, String> autoAnaylizeTemplate(@RequestBody Map map) {
        String jsonStr = (String) map.get("jsonStr");
        JsonElement jsonEle = new JsonParser().parse(jsonStr);
        JsonObject jsonAll = jsonEle.getAsJsonObject();
        jsonAll.remove("sOper"); // 移除"sOper"节点
        JsonObject oldJson = jsonAll.deepCopy();
        String requestJson = JsonUtil.replaceJsonNode(jsonAll).toString();
        // 为了适配autoTestNg,这里还需要将两边的括号{}去掉
        requestJson = requestJson.substring(1,requestJson.length()-1);
        Map<String, String> result = new HashMap<String, String>();
        result.put("template", requestJson);
        result.put("firsthand", oldJson.toString()); // 这里为什么要保留原始报文，且不去掉两边的括号，因为这样前台可以直接反序列化用于后续操作。

        return result;
    }
    @ApiOperation(value = "删除案例模板")
    @PostMapping(path = "/deleteTestCaseTemplate")
    public RespBean deleteTestCaseTemplate(@RequestBody Map map) {

        Integer id = (Integer) map.get("id");
        Integer count = service.deleteTestCaseTemplate(id);
        return RespBean.ok("成功删除[" + count + "]条");
    }

    @ApiOperation(value = "模糊查询案例模板")
    @PostMapping(path = "/selectTestCaseTemplateByFuzzy")
    public List<AutoTestCaseTemplate> selectTestCaseTemplateByFuzzy(@RequestBody Map map) {

        String testCaseTemplateName = (String) map.get("testCaseTemplateName");
        String publicTemplateName = (String) map.get("publicTemplateName");

        return service.selectTestCaseByFuzzy(testCaseTemplateName, publicTemplateName);
    }

    @ApiOperation(value = "解析模板中的参数")
    @PostMapping(path = "/selectTestCaseParamsById")
    public List<String> selectTestCaseParamsById(@RequestBody Map map) {
        Integer id = (Integer) map.get("id");
        return service.selectParamsById(id);
    }

    @ApiOperation(value = "文件导出")
    @GetMapping("/download")
    public String download() {

        AutoTestCaseTemplate test = new AutoTestCaseTemplate();
        List<AutoTestCaseTemplate> testList = new ArrayList<>();
        testList.add(test);
        ResponseEntity<byte[]> responseEntity = PoiUtils.exportToExcel(testList);
        String filename = responseEntity.getHeaders().getContentDisposition().getFilename();
        String out = null;
        try {
            byte[] body = responseEntity.getBody();
            out = new BASE64Encoder().encode(body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return out;
    }

    @ApiOperation(value = "文件上传（只支持Excel）")
    @PostMapping("/upload")
    public RespBean upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {

        int userId = Integer.valueOf(request.getAttribute("userId").toString());
        int count = 0;
        // 上传文件入库
        count = service.upload(file, userId);

        return RespBean.ok("上传成功",count);
    }
}
